package com.example.demo.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Set;

@Repository
public interface MessageRepository extends JpaRepository<Message, Long> {
    Set<Message> findBySenderIdAndReceiverId(long userId, long receiverId);

    // 查询每个发送者 senderId 给每个 receiverId 的最新消息，并且考虑 receiverId 给 senderId 的最新消息
    @Query("SELECT DISTINCT m FROM Message m WHERE (m.sender.id = :senderId OR m.receiver.id = :senderId) " +
            "AND m.id IN (SELECT MAX(m2.id) FROM Message m2 WHERE (m2.sender.id = :senderId OR m2.receiver.id = :senderId) " +
            "GROUP BY CASE " +
            "WHEN m2.sender.id = :senderId THEN m2.receiver.id " +
            "WHEN m2.receiver.id = :senderId THEN m2.sender.id " +
            "END)")
    Set<Message> findLatestMessagesBySenderId(@Param("senderId") Long senderId);
}
